#coding=utf-8

import uuid, os, datetime
from controller.controller_base import *
from conf.settings import BASE_DIR
from common.write_object import read_object

class CommonController(ControllerBase):

    def __init__(self):
        super(CommonController, self).__init__()

    def get_words(self):
        result = {}

        word_all = self.db.session.query(WordCatalog).filter().all()
        for catalog_item in word_all:
            result[catalog_item.catalog_id] = {}
            result[catalog_item.catalog_id]['catalog_name'] = catalog_item.catalog_name
            result[catalog_item.catalog_id]['items'] = []
            for child_item in catalog_item.item_info:
                item = {}
                item['item_id'] = child_item.item_id
                item['item_name'] = child_item.item_name
                result[catalog_item.catalog_id]['items'].append(item)

        return result


    def get_log(self, time_str, line, keyword):
        LOG_DIR = os.path.join(BASE_DIR, 'log')   # 日志目录
        now = datetime.datetime.now()   # 当前字符串
        time_str = time_str or now.strftime("%Y-%m-%d")  # 时间字符串
        log_file_name = time_str + '.log'

        with open(os.path.join(LOG_DIR, log_file_name)) as f:
            read_list = f.readlines()   # 全部文本行list
            if line:
                line = int(line)
                result_read_list = read_list[-line:]    # 倒数切片
            else:
                result_read_list = read_list

        if keyword:
            result_read_list = list(filter(lambda x: keyword in x, result_read_list))

        text = '\n'.join(result_read_list)  # 拼接字符串
        return text


    def get_error_log(self):
        LOG_DIR = os.path.join(BASE_DIR, 'log')   # 日志目录
        now = datetime.datetime.now()   # 当前字符串
        time_str = now.strftime("%Y-%m-%d")  # 时间字符串
        log_file_name = time_str + '.log'

        with open(os.path.join(LOG_DIR, log_file_name)) as f:
            all_content_list = f.readlines()   # 全部文本行list

        trace_slices=[]  # 报错行以及后面50行的切片
        for i, line_text in enumerate(all_content_list):
            if 'Traceback'in line_text:
                trace_slices.append(slice(i, i+50))

        result_read_list=[]
        for trace_slice in trace_slices:

            result_read_list.append('\n'.join(all_content_list[trace_slice]))

        text = '--------------------Traceback分隔线---------------------\n'.join(result_read_list)
        return text

    def read_obj(self, name):
        obj = read_object(name)
        return obj
